import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { Ref } from 'vue'

import { store } from '@/stores'
import { DARK_MODE_KEY, ThemeEnum } from './enums'

const _useDarkStore = defineStore('app', () => {
  // ------------ 颜色主题配置 ------------
  // state
  const themeMode: Ref<ThemeEnum> = ref(ThemeEnum.LIGHT)
  // getter
  function getThemeMode(): 'light' | 'dark' | string {
    return themeMode.value || localStorage.getItem(DARK_MODE_KEY) || themeMode.value
  }

  // action
  function setThemeMode(mode: ThemeEnum): void {
    themeMode.value = mode
    localStorage.setItem(DARK_MODE_KEY, mode)
  }

  function switchMode() {
    const element: HTMLElement = document.body
    if (themeMode.value === 'light') {
      setThemeMode(ThemeEnum.DARK)
    } else {
      setThemeMode(ThemeEnum.LIGHT)
    }
    element.classList.toggle('dark-theme')
  }

  return {
    themeMode,
    getThemeMode,
    setThemeMode,
    switchMode
  }
})

export function useDarkStore() {
  return _useDarkStore(store)
}
